//
//  FLHomeViewController.m
//  FeeLing
//
//  Created by 乔光玉 on 2019/1/2.
//  Copyright © 2019年 大仙儿飘. All rights reserved.
//
#import "ExtAudioConverter.h"
#import "MSAudioConversion.h"
#import "MSBandFile.h"
#import "FLTableViewCell.h"
#import "FLAudioObject.h"
#import "FLAudioMusicDBManager.h"
#import "FLMineViewController.h"
#import "FLHomeViewController.h"
#import "PHAssetModel.h"
#import <AVFoundation/AVAsset.h>
#import <AVFoundation/AVAssetImageGenerator.h>
#import <AVFoundation/AVTime.h>
#import <Photos/Photos.h>
#import "FLDeleView.h"
#import "FLAnainNameView.h"
@interface FLHomeViewController ()<UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate>
{
    UIView *switchView;
    BOOL _isPlaying;
    id _removeTimeObserver;
    FLAnainNameView * _againNameView;
    FLDeleView * _deleView;
    BOOL  _showsecondview;
    
}
@property(nonatomic,strong)UIView * navView;
@property(nonatomic,strong)UILabel * navLabel;
@property(nonatomic,strong)UIButton * userButton;
@property (nonatomic, strong)UITableView *beforeSelectedTableView;
@property (nonatomic, strong)UITableView *beforePlaySelectedTableView;
@property (nonatomic, strong) NSIndexPath *beforeSelectedIndexPath;
@property (nonatomic, strong) NSIndexPath *beforePlaySelectedIndexPath;
@property (nonatomic,strong) AVPlayerItem *playerItem;
@property (nonatomic,strong) AVPlayer *player;
@property (nonatomic, strong) FLTableViewCell *beforeCell;
@property (nonatomic, strong) FLAudioObject *model;
@property (nonatomic, strong)UIScrollView *bgScrollView;
@property (nonatomic, strong)UITableView *firstTableView;

@property (nonatomic, strong)UITableView *thirdTableView;
@property (nonatomic, strong)UITableView *fourTableView;
@property (nonatomic, strong)UIButton *lastSelectedBtn;
@property (nonatomic, strong)UILabel *flyLine;
@property (nonatomic, strong)NSMutableArray *totalSwitchBtns;


@property (nonatomic, strong) NSMutableArray *firstArray;

@property (nonatomic, strong) NSMutableArray *thirdArray;
@property (nonatomic, strong) NSMutableArray *fourArray;

@property (nonatomic, strong)UIImageView * noImageView;
@property (nonatomic, strong)UILabel * noLabelone;
@property (nonatomic, strong)UILabel * noLabeltwo;
@property (nonatomic, strong)UILabel * noaudioLabelone;
@property (nonatomic, strong)UILabel * noaudioLabeltwo;
@end

@implementation FLHomeViewController
- (UIScrollView *)bgScrollView {
    if (!_bgScrollView) {
        _bgScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 64+51, SCREENWIDTH, SCREENHEIGHT-64-51)];
        if (SCREENHEIGHT>800) {
            _bgScrollView.frame =CGRectMake(0, 84+51, SCREENWIDTH, SCREENHEIGHT-84-51);
        }
        _bgScrollView.contentSize = CGSizeMake(SCREENWIDTH*3, 0);
        _bgScrollView.pagingEnabled = YES;
        _bgScrollView.delegate = self;
        _bgScrollView.scrollEnabled = NO;
        
        _bgScrollView.clipsToBounds = NO;
    }
    return _bgScrollView;
}
- (UITableView *)firstTableView {
    if (!_firstTableView) {
        _firstTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.bgScrollView.frame.size.width, self.bgScrollView.frame.size.height) style:UITableViewStylePlain];
        _firstTableView.backgroundColor = [UIColor colorWithHexString:@"#2B2D5C"];
        _firstTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _firstTableView.delegate = self;
        _firstTableView.dataSource = self;
        _firstTableView.hidden = YES;
        _firstTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
       
    }
    return _firstTableView;
}

- (UITableView *)thirdTableView {
    if (!_thirdTableView) {
        _thirdTableView = [[UITableView alloc] initWithFrame:CGRectMake(self.bgScrollView.frame.size.width, 0, self.bgScrollView.frame.size.width, self.bgScrollView.frame.size.height) style:UITableViewStylePlain];
        _thirdTableView.backgroundColor = [UIColor colorWithHexString:@"#2B2D5C"];
        _thirdTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _thirdTableView.delegate = self;
        _thirdTableView.dataSource = self;
         _thirdTableView.hidden = YES;
        _thirdTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
       
    }
    return _thirdTableView;
}
- (UITableView *)fourTableView {
    if (!_fourTableView) {
        _fourTableView = [[UITableView alloc] initWithFrame:CGRectMake(self.bgScrollView.frame.size.width*2, 0, self.bgScrollView.frame.size.width, self.bgScrollView.frame.size.height) style:UITableViewStylePlain];
        _fourTableView.backgroundColor = [UIColor colorWithHexString:@"#2B2D5C"];
         _fourTableView.hidden = YES;
        _fourTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _fourTableView.delegate = self;
        _fourTableView.dataSource = self;
        _fourTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
       
    }
    return _fourTableView;
}
-(void)viewWillAppear:(BOOL)animated{
    
    self.tabBarController.tabBar.hidden = NO;
    
    [_firstArray removeAllObjects];
    [_thirdArray removeAllObjects];
    [_fourArray removeAllObjects];
    [_firstArray addObjectsFromArray:[[FLAudioMusicDBManager sharedManager]getOneoObjectAudiosWith:1]];
    
    [_thirdArray addObjectsFromArray:[[FLAudioMusicDBManager sharedManager]getOneoObjectAudiosWith:4]];
    [_fourArray addObjectsFromArray:[[FLAudioMusicDBManager sharedManager]getOneoObjectAudiosWith:2]];
    [self.firstTableView reloadData];
    [self.thirdTableView reloadData];
    [self.fourTableView reloadData];
    
}
-(void)changeTabBar:(NSNotificationCenter *)notif {
  UIButton * button= (UIButton *) [switchView viewWithTag:12];
    [self didselected:button];
    
}
-(void)shengchenglingsheng{
    
    UIButton * button= (UIButton *) [switchView viewWithTag:13];
    [self didselected:button];
}
-(void)zantingyinyue{
    
    if (_isPlaying) {
        _isPlaying = NO;
        self.player = nil;
        self.playerItem = nil;
        
        FLTableViewCell * becell = (FLTableViewCell *)[self.beforePlaySelectedTableView cellForRowAtIndexPath:self.beforePlaySelectedIndexPath];
        if (becell.playButton.selected) {
            becell.playButton.selected= NO;
        }
    }
    
}
-(void)shengchengshipin{
    UIButton * button= (UIButton *) [switchView viewWithTag:11];
    [self didselected:button];
}
//传入 秒  得到  xx分钟xx秒
-(NSString *)getMMSSFromSS:(NSInteger )seconds{
    
    
    
    //format of minute
    NSString *str_minute ;
    if (seconds/60>=10) {
        str_minute = [NSString stringWithFormat:@"%ld",seconds/60];
    }else{
        str_minute = [NSString stringWithFormat:@"0%ld",seconds/60];
    }
    
    //format of second
    NSString *str_second;
    if (seconds%60>=10) {
        str_second = [NSString stringWithFormat:@"%ld",seconds%60];
    }else{
        str_second = [NSString stringWithFormat:@"0%ld",seconds%60];
    }
    
    //format of time
    NSString *format_time = [NSString stringWithFormat:@"%@:%@",str_minute,str_second];
    
    NSLog(@"format_time : %@",format_time);
    
    return format_time;
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
   
    [[NSNotificationCenter defaultCenter]  addObserver:self selector:@selector(changeTabBar:) name:@"iphonmmme"object:nil];
     [[NSNotificationCenter defaultCenter]  addObserver:self selector:@selector(zantingyinyue) name:@"gerenpush"object:nil];
     [[NSNotificationCenter defaultCenter]  addObserver:self selector:@selector(zantingyinyue) name:@"pinjiepush"object:nil];
     [[NSNotificationCenter defaultCenter]  addObserver:self selector:@selector(zantingyinyue) name:@"bizhipush"object:nil];
    [[NSNotificationCenter defaultCenter]  addObserver:self selector:@selector(zantingyinyue) name:@"add"object:nil];
    [[NSNotificationCenter defaultCenter]  addObserver:self selector:@selector(shengchenglingsheng) name:@"makebee"object:nil];
    [[NSNotificationCenter defaultCenter]  addObserver:self selector:@selector(shengchengshipin) name:@"makeaudio"object:nil];
    
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    self.view.backgroundColor = [UIColor colorWithHexString:@"#2B2D5C"];
    self.navView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 64)];
    self.navView.backgroundColor = [UIColor colorWithHexString:@"32346A"];
    [self.view addSubview:self.navView];
    
    self.navLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 30, SCREENWIDTH, 25)];
    self.navLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size: 18];
    self.navLabel.textAlignment = NSTextAlignmentCenter;
    self.navLabel.textColor = [UIColor whiteColor];
    self.navLabel.text = NSLocalizedString(@"miaobianlingsheng", nil);
    [self.view addSubview:self.navLabel];
    
    self.userButton = [UIButton new];
    self.userButton.frame = CGRectMake(SCREENWIDTH-12-22, 32, 22, 22);
    [self.userButton setImage:[UIImage imageNamed:@"我的"] forState:UIControlStateNormal];
    [self.userButton addTarget:self action:@selector(userButtonclick:) forControlEvents:UIControlEventTouchUpInside];
   // [self.view addSubview:self.userButton];
    if (SCREENHEIGHT>800) {
        self.navView.frame =CGRectMake(0, 0, SCREENWIDTH, 84);
        self.navLabel.frame =CGRectMake(0, 30+20, SCREENWIDTH, 25);
    }
    _firstArray = [NSMutableArray array];
  
    _thirdArray = [NSMutableArray array];
    _fourArray = [NSMutableArray array];
//  AVQuery * avquery  = [AVQuery queryWithClassName:@"lingsheng"];
//
//    [avquery findObjectsInBackgroundWithBlock:^(NSArray * _Nullable objects, NSError * _Nullable error) {
//        NSArray *appLanguages = [[NSUserDefaults standardUserDefaults] objectForKey:@"AppleLanguages"];
//        NSString *languageName = [appLanguages objectAtIndex:0];
//
//        if (objects.count)
//        {
//
//            for (int i=0; i<objects.count; i++) {
//                FLAudioObject * AudioOb = [[FLAudioObject alloc]init];
//                if (![languageName containsString:@"zh"]) {
//                    AudioOb.name =objects[i][@"nameeng"];
//                }else{
//                    AudioOb.name =objects[i][@"name"];
//                }
//
//                AudioOb.time =[self getMMSSFromSS:[objects[i][@"name"] integerValue]];
//                AudioOb.isNetwork = YES;
//                AVFile * file = objects[i][@"sucai"];
//                AudioOb.url = file.url;
//                [_firstArray addObject:AudioOb];
//                 [_firstArray addObjectsFromArray:[[FLAudioMusicDBManager sharedManager]getOneoObjectAudiosWith:1]];
//                [self.firstTableView reloadData];
//            }
//
//
//        }
//
//    }];
   
    [_firstArray addObjectsFromArray:[[FLAudioMusicDBManager sharedManager]getOneoObjectAudiosWith:1]];
    [_thirdArray addObjectsFromArray:[[FLAudioMusicDBManager sharedManager]getOneoObjectAudiosWith:4]];
    [_fourArray addObjectsFromArray:[[FLAudioMusicDBManager sharedManager]getOneoObjectAudiosWith:2]];
   
    
    [self.view addSubview:self.bgScrollView];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.noLabelone = [[UILabel alloc]init];
    self.noLabelone.textAlignment = NSTextAlignmentCenter;
    self.noLabelone.textColor = [UIColor colorWithHexString:@"#7D8CF8"];
    self.noLabelone.font = [UIFont fontWithName:@"PingFangSC-Light" size: 22];
   
    
    self.noLabelone.text = NSLocalizedString(@"noLabelonetext", nil);
    [self.bgScrollView addSubview:self.noLabelone];
    
    
    self.noLabeltwo = [[UILabel alloc]init];
    self.noLabeltwo.textAlignment = NSTextAlignmentCenter;
    self.noLabeltwo.textColor = [UIColor colorWithHexString:@"#7D8CF8"];
    self.noLabeltwo.font = [UIFont fontWithName:@"PingFangSC-Light" size: 22];
    
    
    self.noLabeltwo.text = NSLocalizedString(@"noLabeltwotext", nil);
    [self.bgScrollView addSubview:self.noLabeltwo];
    
    if (self.firstArray.count>0) {
        self.noLabelone.hidden = YES;
        self.noLabeltwo.hidden = YES;
    }else{
        self.noLabelone.hidden = NO;
        self.noLabeltwo.hidden = NO;
    }
    
    self.noaudioLabelone = [[UILabel alloc]init];
    self.noaudioLabelone.textAlignment = NSTextAlignmentCenter;
    self.noaudioLabelone.textColor = [UIColor colorWithHexString:@"#7D8CF8"];
    self.noaudioLabelone.font = [UIFont fontWithName:@"PingFangSC-Light" size: 22];
   
    self.noaudioLabelone.hidden = YES;
    self.noaudioLabelone.text = NSLocalizedString(@"noaudioLabelonetext", nil);
    [self.bgScrollView addSubview:self.noaudioLabelone];
    
    self.noaudioLabeltwo = [[UILabel alloc]init];
    self.noaudioLabeltwo.textAlignment = NSTextAlignmentCenter;
    self.noaudioLabeltwo.textColor = [UIColor colorWithHexString:@"#7D8CF8"];
    self.noaudioLabeltwo.font = [UIFont fontWithName:@"PingFangSC-Light" size: 22];
   
    self.noaudioLabeltwo.hidden = YES;
    self.noaudioLabeltwo.text = NSLocalizedString(@"noaudioLabeltwotext", nil);
    [self.bgScrollView addSubview:self.noaudioLabeltwo];
   
    self.noImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"无铃声状态"]];
   
    self.noImageView.hidden =NO;
    
    [self.bgScrollView addSubview:self.noImageView];
    
    self.noLabelone.frame = CGRectMake(0, 129, SCREENWIDTH, 34);
    self.noLabeltwo.frame = CGRectMake(0, self.noLabelone.bottom, SCREENWIDTH, 34);
    
    self.noImageView.frame = CGRectMake(0, self.noLabeltwo.bottom+76, SCREENWIDTH, 140);
    [self.bgScrollView addSubview:self.firstTableView];
   
    [self.bgScrollView addSubview:self.thirdTableView];
    [self.bgScrollView addSubview:self.fourTableView];
    
    
     [self initUI];
}








- (void)initUI {
    //self.bgScrollView.contentOffset = CGPointMake(0, 0);
    self.totalSwitchBtns = [NSMutableArray array];
    NSArray *switchElement = @[NSLocalizedString(@"minelingsheng", nil), NSLocalizedString(@"pinjielingsheng", nil),NSLocalizedString(@"mineluyin", nil)];
    switchView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, SCREENWIDTH, 51)];
    if (SCREENHEIGHT>800) {
        switchView.frame =CGRectMake(0, 84, SCREENWIDTH, 51);
    }
    switchView.backgroundColor = [UIColor colorWithHexString:@"#2B2D5C"];
    for (int i = 0; i < switchElement.count; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(i*SCREENWIDTH/switchElement.count, 0, SCREENWIDTH/switchElement.count, switchView.frame.size.height);
        [btn setAttributedTitle:[[NSAttributedString alloc] initWithString:switchElement[i] attributes:@{NSFontAttributeName:[UIFont fontWithName:@"PingFangSC-Regular" size: 16], NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#FFFFFF"]}] forState:UIControlStateNormal];
        [btn setAttributedTitle:[[NSAttributedString alloc] initWithString:switchElement[i] attributes:@{NSFontAttributeName:[UIFont fontWithName:@"PingFangSC-Regular" size: 16], NSForegroundColorAttributeName:[UIColor colorWithHexString:@"#FFFFFF"]}] forState:UIControlStateSelected];
        if (i == 0) {
            btn.selected = YES;
            _lastSelectedBtn = btn;
        }
        btn.tag = 11+i;
        [btn addTarget:self action:@selector(didselected:) forControlEvents:UIControlEventTouchUpInside];
        [switchView addSubview:btn];
        [self.totalSwitchBtns addObject:btn];
    }
    _flyLine = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, _lastSelectedBtn.frame.size.width/2.f, 3)];
    _flyLine.backgroundColor = [UIColor colorWithHexString:@"#F63731"];
    _flyLine.center = CGPointMake(_lastSelectedBtn.center.x, _lastSelectedBtn.frame.size.height-_flyLine.frame.size.height/2.f);
    [switchView addSubview:_flyLine];
    
    [self.view addSubview:switchView];
    
    
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    if (self.firstArray.count>0) {
        self.firstTableView.hidden = NO;
    }else{
        self.firstTableView.hidden = YES;
    }
    if (self.thirdArray.count>0) {
        self.thirdTableView.hidden = NO;
    }else{
        self.thirdTableView.hidden = YES;
    }
    if (self.fourArray.count>0) {
        self.fourTableView.hidden = NO;
    }else{
        self.fourTableView.hidden = YES;
    }
    
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView == self.firstTableView) {
        
     return self.firstArray.count;
    }else if (tableView == self.thirdTableView) {
        
        return self.thirdArray.count;
    }else{
        return self.fourArray.count;
        
    }
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
   
    static NSString *cellID = @"FLTableViewCell";
    FLAudioObject * object;
    if (tableView == self.firstTableView) {
        
        object =self.firstArray[indexPath.row];
    }else if (tableView == self.thirdTableView) {
        
        object =self.thirdArray[indexPath.row];
    }else{
        
        object =self.fourArray[indexPath.row];
        
    }
    
    FLTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    
    if (!cell) {
        cell = [[FLTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    cell.biaoti.text =object.name ;
    
    cell.shijian.text = object.time;
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.playBlock = ^(UIButton * sender) {
        
        sender.selected = !sender.selected;
        
        // 更新上一播放中cell播放状态状态
        if (self.beforePlaySelectedIndexPath != nil && self.beforePlaySelectedIndexPath != indexPath) {
            FLTableViewCell * becell = (FLTableViewCell *)[self.beforePlaySelectedTableView cellForRowAtIndexPath:self.beforePlaySelectedIndexPath];
            if (becell.playButton.selected) {
                becell.playButton.selected= NO;
            }
            if (_isPlaying) {
                [self.player pause];
                self->_isPlaying = NO;
            }
            
            
        }
        self.beforePlaySelectedIndexPath = indexPath;
        self.beforePlaySelectedTableView = tableView;
        if (sender.selected) {
            
//            if (object.isNetwork) {
//                NSURL * url  = [NSURL URLWithString:object.url];
//                self.playerItem = [[AVPlayerItem alloc]initWithURL:url];
//                self.player = [[AVPlayer alloc]initWithPlayerItem:self.playerItem];
//
//                [self.player play];
//                self->_isPlaying = YES;
//            }else{
            NSArray  *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
            NSString* path=[paths objectAtIndex:0];
            NSString * movDirectory =  [path stringByAppendingPathComponent:object.localam];
            self.playerItem = [[AVPlayerItem alloc]initWithURL:[NSURL fileURLWithPath:movDirectory]];
            self.player = [[AVPlayer alloc]initWithPlayerItem:self.playerItem];
            
            [self.player play];
            self->_isPlaying = YES;
//            }
            
        }else{
            
            [self.player pause];
            self->_isPlaying = NO;
        }
        
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(playToEnd) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
        
        
        
        
        
    };
    
    cell.setBlock = ^(UIButton * sender) {
      
        NSArray  *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
        NSString* path=[paths objectAtIndex:0];
        NSString * upmovDirectory =  [path stringByAppendingPathComponent:object.localam];
        NSURL *urlee= [NSURL fileURLWithPath:upmovDirectory];
        
        
        NSString * outPut = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, true).firstObject;
        NSString * temp =[NSString stringWithFormat:@"%@.wav",object.name];
        NSString * newaudioPath =[outPut stringByAppendingPathComponent:temp];
        [[NSFileManager defaultManager] removeItemAtPath:newaudioPath error:nil];
        
        
        [MSAudioConversion conversionForWav:urlee output:newaudioPath error:nil];
        
        
        NSString *bandPath = [self generateBandFile:upmovDirectory];
        NSURL *url = [NSURL fileURLWithPath:bandPath];
        NSArray *activityItems = @[url];
        
        //创建系统分享弹窗
        UIActivityViewController*   _activityViewController =[[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities: nil];
       
        
        //弹出系统分享窗口
        [self presentViewController:_activityViewController animated:TRUE completion:nil];
        // 分享之后的回调
        _activityViewController.completionWithItemsHandler = ^(UIActivityType  _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {
            [[NSFileManager defaultManager] removeItemAtPath:bandPath error:nil];
            
            
            
            
            
            
            
        };
        
        
        
    };
    cell.listBlock = ^(UIButton * sender) {
        
        object.isExpanded = !object.isExpanded;
        
        // 更新上一选中cell折展状态
        if (self.beforeSelectedIndexPath != nil && self.beforeSelectedIndexPath != indexPath) {
            FLAudioObject * model1 ;
            if (self.beforePlaySelectedTableView == self.firstTableView) {
                
                model1 =self.firstArray[self.beforeSelectedIndexPath.row];
            }else if (self.beforePlaySelectedTableView == self.thirdTableView) {
                
                model1 =self.thirdArray[self.beforeSelectedIndexPath.row];
            }else{
                
                model1 =self.fourArray[self.beforeSelectedIndexPath.row];
                
            }
            
            if (model1.isExpanded) {
                model1.isExpanded = NO;
            }
        }
        [self.beforePlaySelectedTableView reloadData];
        self.beforeSelectedIndexPath = indexPath;
        self.beforePlaySelectedTableView = tableView;
        [cell refreshHeight];
        
        if (self.beforeCell != nil && self.beforeCell != cell) {
            if (self.beforeCell.isExpanded) {
                [self.beforeCell refreshHeight];
            }
        }
        self.beforeCell = cell;
        
        
        [tableView reloadData];
        
    };
    cell.moreBlock = ^(UIButton * sender) {
        
        if (sender.tag==1) {
            //设置
            
            
            
            NSArray  *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
            NSString* path=[paths objectAtIndex:0];
            NSString * upmovDirectory =  [path stringByAppendingPathComponent:object.localam];
            NSURL *urlee= [NSURL fileURLWithPath:upmovDirectory];
            
            
            NSString * outPut = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, true).firstObject;
            NSString * temp =[NSString stringWithFormat:@"%@.wav",object.name];
            NSString * newaudioPath =[outPut stringByAppendingPathComponent:temp];
            [[NSFileManager defaultManager] removeItemAtPath:newaudioPath error:nil];
            
            
            [MSAudioConversion conversionForWav:urlee output:newaudioPath error:nil];
            
            
            NSString *bandPath = [self generateBandFile:upmovDirectory];
            NSURL *url = [NSURL fileURLWithPath:bandPath];
            NSArray *activityItems = @[url];
            
            //创建系统分享弹窗
            UIActivityViewController*   _activityViewController =[[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities: nil];
            __weak typeof(self) weakself = self;
            //屏蔽分享的第san方App
            // _activityViewController.excludedActivityTypes = @[@"com.tencent.xin.sharetimeline"];
            //
            //弹出系统分享窗口
            [self presentViewController:_activityViewController animated:TRUE completion:nil];
            // 分享之后的回调
            _activityViewController.completionWithItemsHandler = ^(UIActivityType  _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {
                [[NSFileManager defaultManager] removeItemAtPath:bandPath error:nil];
                if (completed) {
                    
                    
                    sender.selected = NO;
                    if (weakself.beforeCell != nil ) {
                        if (weakself.beforeCell.isExpanded) {
                            [weakself.beforeCell refreshHeight];
                        }
                    }
                    
                    NSIndexPath * indexPath = [tableView indexPathForCell:weakself.beforeCell];
                    FLAudioObject * model1;
                    if (tableView == self.firstTableView) {
                        
                        model1 =self.firstArray[indexPath.row];
                    }else if (tableView == self.thirdTableView) {
                        
                        model1 =self.thirdArray[indexPath.row];
                    }else{
                        
                        model1 =self.fourArray[indexPath.row];
                        
                    }
                    if (model1.isExpanded) {
                        model1.isExpanded = NO;
                    }
                    [tableView reloadData];
                    
                    
                    
                }else{
                    
                    
                    sender.selected = NO;
                   
                    
                }
                
                
                
                
                
                
            };
            
            
        }else if (sender.tag==2){
            //重命名
            __weak typeof(self) weakself = self;
            
            self-> _againNameView = [[FLAnainNameView alloc]initWithFrame:[UIScreen mainScreen].bounds];
            
            self-> _againNameView.cancelBlock = ^(UIButton * sen) {
                
                sender.selected = NO;
                __strong __typeof(self) strongSelf = weakself;
                [strongSelf->_againNameView removeFromSuperview];
                
                
            };
            
            self-> _againNameView.tureBlock = ^(UIButton * _Nonnull button, NSString * _Nonnull text) {
                 __strong __typeof(self) strongSelf = weakself;
                if (text.length) {
                    if ([[FLAudioMusicDBManager sharedManager]isExistAudio:text]) {
                        NSLog(@"名字重复");
                        [MBProgressHUD showError:NSLocalizedString(@"mingzichongfu", nil) toView:strongSelf->_againNameView];
                        
                        
                    }else{
                        
                        
                        NSArray  *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
                        NSString* path=[paths objectAtIndex:0];
                        
                        NSString * objecturl = [NSString stringWithFormat:@"/%@.m4a",text];
                        NSString * movDirectory =  [path stringByAppendingPathComponent:objecturl];
                        
                        NSString * upmovDirectory =  [path stringByAppendingPathComponent:object.localam];
                        object.localam=[NSString stringWithFormat:@"%@.m4a",text] ;
                        NSData * data = [NSData dataWithContentsOfFile:upmovDirectory];
                       [strongSelf creatFileWithPath:movDirectory];
                       [strongSelf saveFile:movDirectory withData:data];
                        
                        
                        [strongSelf removeFileOfPath:upmovDirectory];
                        object.url = objecturl;
                        [[FLAudioMusicDBManager sharedManager]deleteAudioWith:object.name];
                        object.name = text;
                        [[FLAudioMusicDBManager sharedManager] insertAudioWith:object];
                        cell.playButton.selected = NO;
                        sender.selected = NO;
                        
                        
                        if (strongSelf->_isPlaying) {
                            [weakself.player pause];
                            strongSelf->_isPlaying = NO;
                            weakself.player = nil;
                            weakself.playerItem = nil;
                            
                        }
                        
                        [strongSelf->_againNameView removeFromSuperview];
                        
                        [tableView reloadData];
                        
                        
                    }
                    
                }else{
                    [MBProgressHUD showError:NSLocalizedString(@"pleaserut", nil) toView:strongSelf->_againNameView];
                    
                }
            };
            [self.view addSubview:self->_againNameView];
            
        }else{
            //删除
            self->_deleView = [[FLDeleView alloc]initWithFrame:[UIScreen mainScreen].bounds];
            __weak typeof(self) weakself = self;
            self->_deleView.cancelBlock = ^(UIButton * button) {
                
                sender.selected = NO;
                __strong __typeof(self) strongSelf = weakself;
                [strongSelf->_deleView removeFromSuperview];
                
                
                
            };
            self->_deleView.tureBlock = ^(UIButton * button) {
                
                if (self->_isPlaying) {
                    [self.player pause];
                    self->_isPlaying = NO;
                    self.player = nil;
                    self.playerItem = nil;
                    
                }
                
                if (weakself.beforeCell != nil ) {
                    if (weakself.beforeCell.isExpanded) {
                        [weakself.beforeCell refreshHeight];
                    }
                }
                sender.selected = NO;
                __strong __typeof(self) strongSelf = weakself;
                [strongSelf->_deleView removeFromSuperview];
                [[FLAudioMusicDBManager sharedManager] deleteAudioWith:object.name];
                NSInteger row ;
                if (tableView == self.firstTableView) {
                    
                    row =[weakself.firstArray indexOfObject:object];
                }else if (tableView == self.thirdTableView) {
                    
                    row =[weakself.thirdArray indexOfObject:object];
                }else{
                    
                    row =[weakself.fourArray indexOfObject:object];
                    
                }
                if ((weakself.beforeSelectedIndexPath!=nil&&weakself.beforeSelectedIndexPath.row==row)&&weakself.beforePlaySelectedTableView==tableView) {
                    
                    weakself.beforeSelectedIndexPath=nil;
                }
                if (weakself.beforePlaySelectedTableView == self.firstTableView) {
                    
                   [weakself.firstArray removeObject:object];
                }else if (weakself.beforePlaySelectedTableView == self.thirdTableView) {
                    
                    [weakself.thirdArray removeObject:object];
                }else{
                    
                    [weakself.fourArray removeObject:object];
                    
                }
                
                if (tableView == self.firstTableView) {
                    
                    if (weakself.firstArray.count) {
                        [tableView reloadData];
                        weakself.firstTableView.hidden = NO;
                        weakself.noImageView.hidden = YES;
                        weakself.noLabelone.hidden = YES;
                        weakself.noLabeltwo.hidden = YES;
                        weakself.noaudioLabelone.hidden = YES;
                        weakself.noaudioLabeltwo.hidden = YES;
                        
                    }else{
                        
                        weakself.noImageView.hidden = NO;
                        weakself.noLabelone.hidden = NO;
                        weakself.noLabeltwo.hidden = NO;
                        weakself.noaudioLabelone.hidden = YES;
                        weakself.noaudioLabeltwo.hidden = YES;
                        weakself.firstTableView.hidden = YES;
                        weakself.noLabelone.frame = CGRectMake(0, 129, SCREENWIDTH, 34);
                        weakself.noLabeltwo.frame = CGRectMake(0, self.noLabelone.bottom, SCREENWIDTH, 34);
                        
                        weakself.noImageView.frame = CGRectMake(0, self.noLabeltwo.bottom+76, SCREENWIDTH, 140);
                    }
                   
                }else if (tableView == self.thirdTableView) {
                    if (weakself.thirdArray.count) {
                        [tableView reloadData];
                        weakself.thirdTableView.hidden = NO;
                        weakself.noImageView.hidden = YES;
                        weakself.noLabelone.hidden = YES;
                        weakself.noLabeltwo.hidden = YES;
                        weakself.noaudioLabelone.hidden = YES;
                        weakself.noaudioLabeltwo.hidden = YES;
                        
                    }else{
                        
                        weakself.noImageView.hidden = NO;
                        weakself.noLabelone.hidden = NO;
                        weakself.noLabeltwo.hidden = NO;
                        weakself.noaudioLabelone.hidden = YES;
                        weakself.noaudioLabeltwo.hidden = YES;
                        weakself.thirdTableView.hidden = YES;
                        weakself.noLabelone.frame = CGRectMake(SCREENWIDTH*1, 129, SCREENWIDTH, 34);
                        weakself.noLabeltwo.frame = CGRectMake(SCREENWIDTH*1, self.noLabelone.bottom, SCREENWIDTH, 34);
                        
                        weakself.noImageView.frame = CGRectMake(SCREENWIDTH*1, self.noLabeltwo.bottom+76, SCREENWIDTH, 140);
                    }
                   
                }else{
                    
                    if (weakself.fourArray.count) {
                        [tableView reloadData];
                        weakself.fourTableView.hidden = NO;
                        weakself.noImageView.hidden = YES;
                        weakself.noLabelone.hidden = YES;
                        weakself.noLabeltwo.hidden = YES;
                        weakself.noaudioLabelone.hidden = YES;
                        weakself.noaudioLabeltwo.hidden = YES;
                        
                    }else{
                        
                        weakself.noImageView.hidden = NO;
                        weakself.noLabelone.hidden = YES;
                        weakself.noLabeltwo.hidden = YES;
                        weakself.noaudioLabelone.hidden = NO;
                        weakself.noaudioLabeltwo.hidden = NO;
                        weakself.fourTableView.hidden = YES;

                        weakself.noaudioLabelone.frame = CGRectMake(SCREENWIDTH*2, 129, SCREENWIDTH, 34);
                        weakself.noaudioLabeltwo.frame = CGRectMake(SCREENWIDTH*2, self.noaudioLabelone.bottom, SCREENWIDTH, 34);
                        weakself.noImageView.frame = CGRectMake(SCREENWIDTH*2, self.noaudioLabeltwo.bottom+76, SCREENWIDTH, 140);
                    }
                    
                }
                
                
                
            };
            [self.view addSubview:self->_deleView];
            
            
        }
        
        
    };
    
    return cell;
}
//生成新的BandFilePath
- (NSString *)generateBandFile:(NSString *)filePath{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    NSString *fileName = [[filePath lastPathComponent] stringByDeletingPathExtension];
    NSString* cachePath=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES) objectAtIndex:0];
    NSString *tmpBandDir = [cachePath stringByAppendingPathComponent:fileName];
    if ([fileManager fileExistsAtPath:tmpBandDir]) {
        [fileManager removeItemAtPath:tmpBandDir error:nil];
    }
    
    NSString *bandFilePath = [[NSBundle mainBundle] pathForResource:
                              @"bandName" ofType:@"band"];
    if([fileManager fileExistsAtPath:bandFilePath]){
        [fileManager copyItemAtPath:bandFilePath toPath:tmpBandDir error:nil];
    }
    
    NSString *ringtonefile = [tmpBandDir stringByAppendingPathComponent:@"Media/ringtone.aiff"];
    ExtAudioConverter* converter = [[ExtAudioConverter alloc] init];
    converter.inputFile = filePath;
    converter.outputFile = ringtonefile;
    converter.outputFileType = kAudioFileAIFFType;
    if ([converter convert]) {
        NSLog(@"转化成功");
    }
    
    NSString *bandDir = [tmpBandDir stringByAppendingString:@".band"];
    [fileManager moveItemAtPath:tmpBandDir toPath:bandDir error:nil];
    
    return bandDir;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    FLAudioObject * model ;
    
    if (tableView == self.firstTableView) {
        
        model =self.firstArray[indexPath.row];
    }else if (tableView == self.thirdTableView) {
        
        model =self.thirdArray[indexPath.row];
    }else{
        
        model =self.fourArray[indexPath.row];
        
    }
    
    if (model.isExpanded) {
        
        return 132;
    }
    else {
        return 66;
    }
}

- (void)playToEnd{
    __weak typeof(self) weakSelf = self;
    dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.01* NSEC_PER_SEC)); dispatch_after(delayTime, dispatch_get_main_queue(), ^{
        __strong typeof(weakSelf) strongSelf = weakSelf;
        
        strongSelf->_isPlaying = NO;
        weakSelf.player = nil;
        weakSelf.playerItem = nil;
       
            FLTableViewCell * becell = (FLTableViewCell *)[self.beforePlaySelectedTableView cellForRowAtIndexPath:self.beforePlaySelectedIndexPath];
            if (becell.playButton.selected) {
                becell.playButton.selected= NO;
            }
//        }else if (_lastSelectedBtn.tag==12){
//            FLTableViewCell * becell = (FLTableViewCell *)[self.thirdTableView cellForRowAtIndexPath:self.beforePlaySelectedIndexPath];
//            if (becell.playButton.selected) {
//                becell.playButton.selected= NO;
//            }
//        }else if (_lastSelectedBtn.tag==13){
//            FLTableViewCell * becell = (FLTableViewCell *)[self.fourTableView cellForRowAtIndexPath:self.beforePlaySelectedIndexPath];
//            if (becell.playButton.selected) {
//                becell.playButton.selected= NO;
//            }
//        }
        
        
    });
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
//    NSUInteger index =  (NSUInteger)((scrollView.contentOffset.x+5) / SCREENWIDTH);
//    UIButton *currentBtn = self.totalSwitchBtns[index];
//    if (_lastSelectedBtn == currentBtn) {
//        return;
//    }
//    [UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
//        self.flyLine.center = CGPointMake(currentBtn.center.x, self.flyLine.center.y);
//    } completion:^(BOOL finished) {
//        _lastSelectedBtn.selected = !_lastSelectedBtn.selected;
//        currentBtn.selected = !currentBtn.selected;
//        _lastSelectedBtn = currentBtn;
//        
//        
//        
//    }];
}
- (void)didselected:(UIButton *)button {
    if (_lastSelectedBtn == button) {
        return;
    }
    NSInteger index = [self.totalSwitchBtns indexOfObject:button];
    if (index < 0 || index > self.totalSwitchBtns.count-1) {
        return;
    }
    if (button.center.x != self.flyLine.center.x) {
        button.selected = !button.selected;
        self.lastSelectedBtn.selected = !self.lastSelectedBtn.selected;
        [UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            self.flyLine.center = CGPointMake(button.center.x, self.flyLine.center.y);
            self.bgScrollView.contentOffset = CGPointMake(SCREENWIDTH*index, 0);
        } completion:^(BOOL finished) {
            self.lastSelectedBtn = button;
            if (_lastSelectedBtn.tag == 11) {
                
                if (self.firstArray.count) {
                    
                    self.firstTableView.hidden = NO;
                    self.noImageView.hidden = YES;
                    self.noLabelone.hidden = YES;
                    self.noLabeltwo.hidden = YES;
                    self.noaudioLabelone.hidden = YES;
                    self.noaudioLabeltwo.hidden = YES;
                    
                }else{
                    
                    self.noImageView.hidden = NO;
                    self.noLabelone.hidden = NO;
                    self.noLabeltwo.hidden = NO;
                    self.noaudioLabelone.hidden = YES;
                    self.noaudioLabeltwo.hidden = YES;
                    self.firstTableView.hidden = YES;
                    self.noLabelone.frame = CGRectMake(0, 129, SCREENWIDTH, 34);
                    self.noLabeltwo.frame = CGRectMake(0, self.noLabelone.bottom, SCREENWIDTH, 34);
                    
                    self.noImageView.frame = CGRectMake(0, self.noLabeltwo.bottom+76, SCREENWIDTH, 140);
                }
                
            }else if (_lastSelectedBtn.tag == 12) {
                if (self.thirdArray.count) {
                    
                    self.thirdTableView.hidden = NO;
                    self.noImageView.hidden = YES;
                    self.noLabelone.hidden = YES;
                    self.noLabeltwo.hidden = YES;
                    self.noaudioLabelone.hidden = YES;
                    self.noaudioLabeltwo.hidden = YES;
                    
                }else{
                    
                    self.noImageView.hidden = NO;
                    self.noLabelone.hidden = NO;
                    self.noLabeltwo.hidden = NO;
                    self.noaudioLabelone.hidden = YES;
                    self.noaudioLabeltwo.hidden = YES;
                    self.thirdTableView.hidden = YES;
                    self.noLabelone.frame = CGRectMake(SCREENWIDTH*1, 129, SCREENWIDTH, 34);
                    self.noLabeltwo.frame = CGRectMake(SCREENWIDTH*1, self.noLabelone.bottom, SCREENWIDTH, 34);
                    
                    self.noImageView.frame = CGRectMake(SCREENWIDTH*1, self.noLabeltwo.bottom+76, SCREENWIDTH, 140);
                }
                
            }else{
                
                if (self.fourArray.count) {
                    
                    self.fourTableView.hidden = NO;
                    self.noImageView.hidden = YES;
                    self.noLabelone.hidden = YES;
                    self.noLabeltwo.hidden = YES;
                    self.noaudioLabelone.hidden = YES;
                    self.noaudioLabeltwo.hidden = YES;
                    
                }else{
                    
                    self.noImageView.hidden = NO;
                    self.noLabelone.hidden = YES;
                    self.noLabeltwo.hidden = YES;
                    self.noaudioLabelone.hidden = NO;
                    self.noaudioLabeltwo.hidden = NO;
                    self.fourTableView.hidden = YES;
                    
                    self.noaudioLabelone.frame = CGRectMake(SCREENWIDTH*2, 129, SCREENWIDTH, 34);
                    self.noaudioLabeltwo.frame = CGRectMake(SCREENWIDTH*2, self.noaudioLabelone.bottom, SCREENWIDTH, 34);
                    self.noImageView.frame = CGRectMake(SCREENWIDTH*2, self.noaudioLabeltwo.bottom+76, SCREENWIDTH, 140);
                }
                
            }
        }];
        
    }
}
-(void)userButtonclick:(UIButton *)sender{
    
    self.hidesBottomBarWhenPushed=YES;
    FLMineViewController * vc =[[FLMineViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
    self.hidesBottomBarWhenPushed=NO;
}
-(BOOL)removeFileOfPath:(NSString *)filePath
{
    BOOL flag = YES;
    NSFileManager *fileManage = [NSFileManager defaultManager];
    if ([fileManage fileExistsAtPath:filePath]) {
        if (![fileManage removeItemAtPath:filePath error:nil]) {
            flag = NO;
        }
    }
    return flag;
}
//创建文件
-(BOOL)creatFileWithPath:(NSString *)filePath
{
    BOOL isSuccess = YES;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL temp = [fileManager fileExistsAtPath:filePath];
    if (temp) {
        return YES;
    }
    NSError *error;
    //stringByDeletingLastPathComponent:删除最后一个路径节点
    NSString *dirPath = [filePath stringByDeletingLastPathComponent];
    isSuccess = [fileManager createDirectoryAtPath:dirPath withIntermediateDirectories:YES attributes:nil error:&error];
    if (error) {
        NSLog(@"creat File Failed. errorInfo:%@",error);
    }
    if (!isSuccess) {
        return isSuccess;
    }
    isSuccess = [fileManager createFileAtPath:filePath contents:nil attributes:nil];
    return isSuccess;
}

//保存文件
-(BOOL)saveFile:(NSString *)filePath withData:(NSData *)data
{
    BOOL ret = YES;
    ret = [self creatFileWithPath:filePath];
    if (ret) {
        ret = [data writeToFile:filePath atomically:YES];
        if (!ret) {
            NSLog(@"%s Failed",__FUNCTION__);
        }
    } else {
        NSLog(@"%s Failed",__FUNCTION__);
    }
    return ret;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
